package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.SetmealEnableFailedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.service.SetmealService;
import com.sky.vo.DishVO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private SetmealService setmealService;

    /**
     * 新增菜品和对应的口味
     *
     * @param dishDTO
     */
    @Override
    @Transactional
    public void insertDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //向菜品表插入1条数据
        dishMapper.insertDish(dish);
        //获取insert语句生成的主键值
        Long id = dish.getId();
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors == null || flavors.isEmpty()){
            return;
        }
        flavors.forEach(flavor ->{
            flavor.setDishId(id);
        });
        //向口味表插入n条数据
        dishFlavorMapper.insertDishFlavor(flavors);

    }

    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult searchDishes(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());

        Page<DishVO> page = dishMapper.searchDishes(dishPageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }


    /**
     * 菜品批量删除
     *
     * @param ids
     */
    @Override
    @Transactional
    public void deleteDishes(List<Long> ids) {
        for (Long id : ids) {
            //判断当前菜品是否能够删除---是否存在起售中的菜品？？
           Dish dish = dishMapper.searchDishById(id);
           if(dish.getStatus() == StatusConstant.ENABLE){
               //当前菜品处于起售中，不能删除
               throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
           }
            //判断当前菜品是否能够删除---是否被套餐关联了？？
           Integer integer = setmealDishMapper.countSetmeal(id);
           if(integer > 0){
               //当前菜品被套餐关联了，不能删除
               throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
           }
        }
        //删除菜品表中的菜品数据
        dishMapper.deleteDishes(ids);

        //关联的口味也要删掉
        for (Long id : ids) {
            dishFlavorMapper.deleteDishFavorById(id);
        }

    }

    /**
     * 根据id查询菜品和对应的口味数据
     *
     * @param id
     * @return
     */
    @Override
    public DishVO searchDishById(Long id) {
        //根据id查询菜品数据
        Dish dish = dishMapper.searchDishById(id);
        //根据菜品id查询口味数据
        List<DishFlavor> dishFlavors = dishFlavorMapper.searchDishFlavorById(id);

        //将查询到的数据封装到VO
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }


    /**
     * 根据id修改菜品基本信息和对应的口味信息
     *
     * @param dishDTO
     */
    @Override
    public void updateDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);

        //修改菜品表基本信息
        dishMapper.updateDish(dish);

        //删除原有的口味数据
        dishFlavorMapper.deleteDishFavorById(dish.getId());


        //重新插入口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors == null || flavors.isEmpty()){
            return;
        }
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dish.getId());//重新增加的口味数据没有id，需要获取
        }

        //向口味表插入n条数据
        dishFlavorMapper.insertDishFlavor(flavors);


    }

    /**
     * 菜品起售停售
     * @param status
     * @param id
     */
    @Override
    public void updateDishStatus(Integer status, Long id) {
        Dish dish = new Dish();
        dish.setStatus(status);
        dish.setId(id);
        dishMapper.updateDish(dish);

        //如果菜品停售，对应的套餐也要停售
        if (status.equals(StatusConstant.DISABLE)) {
            List<Map> setmealStatuss = dishMapper.searchSetmealStatusByDishId(id);

            setmealStatuss.forEach(setmealStatus -> {
                log.info("集合怎么说：{}",setmealStatus);
                if (setmealStatus.get("setmealStatus").equals(StatusConstant.ENABLE)) {
                    Long setmealId = Long.valueOf(setmealStatus.get("setmealId").toString());
                    setmealService.updateSetmealStatus(StatusConstant.DISABLE, setmealId);
                }
            });
        }
    }

    /**
     * 根据菜品分类id查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> searchDishByCategoryId(Long categoryId) {
        List<DishVO> dishes = dishMapper.searchDishByCategoryId(categoryId);
        System.out.println(dishes);
        return dishes;
    }



}
